package com.sp.homework;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 服务端
 * 1. 使用字符流的方式, 编写一个客户端程序和服务端程序
 * 2. 客户端发送"name", 服务端接收到后, 返回"我是nova", nova是你自己的名字
 * 3. 客户端发送"hobby", 服务端接收到后, 返回"编写java程序"
 * 4. 不是这两个问题, 回复 "你说啥呢"
 */
public class Homework01Server {
    public static void main(String[] args) throws IOException {
        //在本机的9999端口监听
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("服务端, 在9999端口监听, 等待连接");

        Socket socket = serverSocket.accept();
        System.out.println("服务端socket = " + socket.getClass());

        InputStream inputStream = socket.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        OutputStream outputStream = socket.getOutputStream();
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));

        boolean flag = true;
        while (flag) {
            String s = bufferedReader.readLine();
            if (s.equals("name")){
                bufferedWriter.write("我是nova");
            } else if (s.equals("hobby")) {
                bufferedWriter.write("编写java程序");
            } else if (s.equals("q")) {
                bufferedWriter.write("正在关闭服务端");
                break;
            } else {
                bufferedWriter.write("你说啥");
            }
            bufferedWriter.newLine();
            bufferedWriter.flush();
        }

        bufferedWriter.newLine();
        bufferedWriter.flush();

        bufferedWriter.close();
        bufferedReader.close();
        socket.close();
        serverSocket.close();

        System.out.println("服务端已退出");
    }
}
